package com.demo.handphone.handphone;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.device.ScanDevice;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

//import com.duma.ld.mylibrary.SwitchView;
import com.demo.handphone.handphone.response.CheckTicketResponse;
import com.demo.handphone.handphone.response.GateListResponse;
import com.demo.handphone.handphone.utils.CheckCardTimeUtils;
import com.demo.handphone.handphone.utils.DateUtils;
import com.demo.handphone.handphone.utils.SPUtils;
import com.demo.handphone.handphone.utils.StringUtils;
import com.demo.handphone.handphone.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import lib.kingja.switchbutton.SwitchMultiButton;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView img_ip;
    private boolean isIPset;
    private boolean unBind;
    private TextView tv_remainCount;
    private String barcode = "";
    private EditText etTest;

    /**********************语音合成**********************/
    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                /*
               int supported = mSpeech.setLanguage(Locale.ENGLISH);
                if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
                   Toast.makeText(MainActivity.this, "不支持当前语言！", Toast.LENGTH_SHORT).show();
                   Log.i(TAG, "onInit: 支持当前选择语言");
               }else{

               }
               */
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    private static final String TAG = "MainActivity";
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调
    /****************************************************/
    public boolean bNeedCheckTicket = true;    //检票标志位
    private int periodCount = 3;                //默认3s检一次
    private TextView tv1, tv2;
    private ImageView img_link;
    private ImageView img_status;
    private TextView tv_terminal, tv_ticketNO, tv_time, tv_status, tv_name, tv_people;
    private TextView tv_pCount;
    private TextView tv_delete;
    private PopupWindow popupWindow;
    private int screenWidth, screenHeight;
    GateListResponse gateListResponse;
    List<GateListResponse.GateInfoListBean> list;

    SharedPreferences sp;
    SharedPreferences.Editor edit;
    private EditText et_input;
    //    SwitchView switchView;
    SwitchMultiButton mSwitchMultiButton;

    private static final int ReadQR = 1;
    // NFCstart
    protected NfcAdapter nfcAdapter;
    protected PendingIntent pendingIntent;
    // NFCend
    // 扫描二维码start
    private ScanDevice sm;
    private final static String SCAN_ACTION = "scan.rcv.message";
    private String barcodeStr; // 二维码值
    // 扫描二维码end
    private final String idSerialName = "/dev/ttyS2";
    private final int idBaudrate = 115200;
    private IDCardReader idCardReader = null;
    private String timestamp = ""; // 时间戳
    private boolean bopen = false;
    int count = 0;

    //Handler 机制
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ReadQR:
                    ToastUtil.showToast("这里是Handler");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题栏
        setContentView(R.layout.activity_main);

        sp = getSharedPreferences("position", Context.MODE_PRIVATE);
        edit = sp.edit();
        //获取sp中存储的扫描票数
        count = sp.getInt("count", 0);
        // 初始化身份证模块start
        startIDCardReader();


        // 扫描二维码start
//        try{
//            sm = new ScanDevice();
//            sm.setOutScanMode(0); //1 键盘输出；0 广播方式。
//            boolean scanPowerState = sm.isScanOpened();
//            if (!scanPowerState) {
//                sm.openScan();
//            }
//        }catch (Exception e){
//            LogHelper.v("二维码 初始化失败");
//            ToastUtil.showToast("二维码 初始化失败");
//        }


        //Get nfc adapter.
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        try {
            checkNfc();
        } catch (Exception e) {
            System.out.println("nfc出现问题");
        }
        onNewIntent(getIntent());
        // 注册二维码服务
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        registerReceiver(mScanReceiver, filter);
        // 身份证线程
        OnBnOpen();
        new Thread(new ThreadRun()).start();
        initView();
        //获取TTS引擎
        mSpeech = new TextToSpeech(MainActivity.this, new TTSListener());

        isIPset = sp.getBoolean("isIPset", false);
        if (!sp.getString("ip", "").equals("")) {
//            拼接IP地址
            BaseURL.SERVER_URL = sp.getString("ip", "");
//            BaseURL.SERVER_URL = BaseURL.SERVER_URL;
//            getGateList();
            getGateListHttps();
        }

        //测试
//        checkQRCodeHttps("呵呵哒");

    }

    /**
     * 二维码广播
     */
//    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//
//            byte[] barocode = intent.getByteArrayExtra("barocode");
//            int barocodelen = intent.getIntExtra("length", 0);
//            byte temp = intent.getByteExtra("barcodeType", (byte) 0);
//            android.util.Log.i("debug", "----codetype--" + temp);
//            barcodeStr = new String(barocode, 0, barocodelen); // 获取到二维码值
//            if (!StringUtils.isEmpty(barcodeStr)) {
//                // 判断是否满足检票间隔时间 5 秒钟
//                if (!ticketInterval(barcodeStr)) {
//                    return;
//                }
//            }
//            barcodeStr = barcodeStr.replaceAll("\r|\n|\t", "");
////            ToastUtil.showToast("二维码 ：" + barcodeStr);
//
//            sm.stopScan();
//
//            checkQRCode(barcodeStr);
//
//        }
//    };

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //得到二维码后锁住Trigger

            if (bNeedCheckTicket) {
                bNeedCheckTicket = false;
                //清空显示
//                clearTiketInfo();

                // TODO Auto-generated method stub
//                byte[] barocode = intent.getByteArrayExtra("barocode");
//                System.out.print(barocode);
//                int barocodelen = intent.getIntExtra("length", 0);
//                byte temp = intent.getByteExtra("barcodeType", (byte) 0);
//                barcodeStr = new String(barocode, 0, barocodelen);
//
//                //gLogger.debug("barcodeStr:" + barcodeStr);
//
////                strTicketCode.setText(barcodeStr);
//
//                if (barcodeStr != null && !barcodeStr.equals(""))//&& barcodeStrAgain != barcodeStr
//                {
////                    checkQRCode(barcodeStr);
//                    checkQRCodeHttps(barcodeStr);
//                }
                //定时线程启动下次检票
                TriggerThread();
            } else {
//                setSysstatus("请稍等...");
                ToastUtil.showToast("请稍等...");
            }
        }

    };

    //定时器实现防连刷的功能
    public void TriggerThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long count = 0;
                while (true) {
                    if (periodCount <= count) {
//                        etTest.requestFocus();
                        bNeedCheckTicket = true;
                        break;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }).start();
    }


    /**
     * 判断上一次检票时间间隔是否满足要求
     *
     * @param obj 二维码、身份证、IC卡
     * @return true:说明可以执行，false:说明不可以执行
     */
    private boolean ticketInterval(String obj) {
        CheckCardTime checkCardTime = CheckCardTimeUtils.getCheckCardTime();
        if (checkCardTime != null && !StringUtils.isEmpty(checkCardTime.getCardNo()) && checkCardTime.getLastCheckTime() != null && obj.equals(checkCardTime.getCardNo())) {
            int dateFlag = DateUtils.compareToSecond(DateUtils.getDayAfterSecond(checkCardTime.getLastCheckTime(), Constants.WAIT_SECOND), DateUtils.now());
            if (dateFlag > 0) { // 该卡在指定时间执行过
                return false;
            }
        }
        // 保存这次检票时间
        CheckCardTimeUtils.getInstance().updateCheckCardTime(new CheckCardTime(obj, DateUtils.now()));
        return true;
    }

    /**
     * 检查NFC是否打开
     */
    @SuppressLint("NewApi")
    protected void checkNfc() {
        if (!nfcAdapter.isEnabled()) {
            startActivity(new Intent(
                    android.provider.Settings.ACTION_NFC_SETTINGS));
        }
    }


    private void startIDCardReader() {
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_SERIAL_SERIALNAME, idSerialName);
        idrparams.put(ParameterHelper.PARAM_SERIAL_BAUDRATE, idBaudrate);
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.SERIALPORT, idrparams);
    }

    private static boolean flag = false; // 线程是否结束标志

    private static boolean threadFlag = false; // 线程是否执行

    private class ThreadRun implements Runnable {

        @Override
        public void run() {

            while (true) {
                try {
                    if (flag) {
                        break;
                    }
                    if (!threadFlag) { // 不执行读身份证操作
                        Thread.sleep(200);
                        continue;
                    }
                    Log.i(Constants.ACTIVITY_TAG, "读取身份证开始==========================");
                    OnBnRead();
                    Log.i(Constants.ACTIVITY_TAG, "读取身份证结束==========================");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // power on
        try {
            FileWriter localFileWriterOff = new FileWriter(new File(
                    "/proc/gpiocontrol/set_id"));
            localFileWriterOff.write("1");
            localFileWriterOff.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // NFC
        if (nfcAdapter != null) {
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, CardManager.FILTERS, CardManager.TECHLISTS);
        }
    }

    public void Authenticate() {
        try {
            idCardReader.findCard(0);
            idCardReader.selectCard(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开身份证模块
     */
    public void OnBnOpen() {
        try {
            if (bopen) return;
            idCardReader.open(0);
            bopen = true;
//            threadFlag=true; 读取身份证的开关

//            textView.setText("连接设备成功");
        } catch (IDCardReaderException e) {
//            textView.setText("关闭设备成功");
            LogHelper.d("连接设备失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }

    public void OnBnRead() {
//        if(TimeUtils.isFastClick()) return;
        try {
            if (!bopen) {
//                Toast toast = Toast.makeText(getApplicationContext(), "身份证驱动为连接！", 50);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
                ToastUtil.showToast("身份证驱动未连接！");
//                textView.setText("请先连接设备");
            }
            Authenticate();
            int ret = idCardReader.readCardEx(0, 1);
            if (1 == ret) {
                IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                final String ID = idCardInfo.getId();
                if (!StringUtils.isEmpty(ID)) {
                    // 判断是否满足检票间隔时间 5 秒钟
                    if (!ticketInterval(ID)) {

                        return;
                    }

                }
            }
        } catch (IDCardReaderException e) {
//            textView.setText("读卡失败");
            LogHelper.d("读卡失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }

    /**
     * 接收NFC读取的卡号
     */
    @SuppressLint("NewApi")
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {

        } else {
            if (tag != null) {
                String[] techList = tag.getTechList();
                StringBuffer techString = new StringBuffer();
                for (int i = 0; i < techList.length; i++) {
                    techString.append(techList[i]);
                    techString.append(";\n");
                }
                //Show card id.
                byte[] id = tag.getId();
                String cardNo = ByteArrayToHexString(id);
                String tempCardNo = "";
                for (int i = 0, j = 1; i < cardNo.length(); i += 2, j++) {
                    tempCardNo = cardNo.substring(i, 2 * j) + tempCardNo;
                }
                cardNo = tempCardNo;
                if (!StringUtils.isEmpty(cardNo)) {
                    // 判断是否满足检票间隔时间 5 秒钟
                    if (!ticketInterval(cardNo)) {
                        return;
                    }
                    cardNo = StringUtils.toRadix(cardNo, 16);
//                    ToastUtil.showToast("" + cardNo);

                    checkICCard(cardNo);

                }
            }

        }
    }

    /**
     * 卡号转义
     *
     * @param inarray
     * @return
     */
    protected String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F"};
        String out = "";
        for (j = 0; j < inarray.length; ++j) {
            in = inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    private void initView() {

        WindowManager manager = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        Point point = new Point();
        if (Build.VERSION.SDK_INT < 17) {
            display.getSize(point);
        } else {
            display.getRealSize(point);
        }
        screenWidth = point.x;
        screenHeight = point.y;

        mSwitchMultiButton = (SwitchMultiButton) findViewById(R.id.switchmultibutton);
        mSwitchMultiButton.setText("全检", "部分检").setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                if (position == 1) {
                    //如果是1  那么就是部分检票
                    et_input.setText("");
                    et_input.setEnabled(true);
                    et_input.setBackground(new ColorDrawable(Color.parseColor("#ffffff")));
//                    etTest.requestFocus();
                } else {
                    et_input.setText("");
                    et_input.setBackground(new ColorDrawable(0xaa000000));
                    et_input.setEnabled(false);
//                    etTest.requestFocus();
                }
            }
        });


        tv1 = (TextView) findViewById(R.id.unbind_tv1);
        tv2 = (TextView) findViewById(R.id.unbind_tv2);
        img_link = (ImageView) findViewById(R.id.ma_img_link);
        img_status = (ImageView) findViewById(R.id.img_status);
        tv_terminal = (TextView) findViewById(R.id.ma_tv_terminal);
        tv_ticketNO = (TextView) findViewById(R.id.ma_tv_ticketNO);
        tv_time = (TextView) findViewById(R.id.ma_tv_time);
        tv_status = (TextView) findViewById(R.id.ma_tv_status);
        tv_name = (TextView) findViewById(R.id.ma_tv_name);
        tv_people = (TextView) findViewById(R.id.ma_tv_people);
        tv_pCount = (TextView) findViewById(R.id.ma_tv_pCount);
        tv_delete = (TextView) findViewById(R.id.ma_tv_delete);
        et_input = (EditText) findViewById(R.id.ma_et_input);
        img_ip = (ImageView) findViewById(R.id.img_ip);
        etTest = (EditText) findViewById(R.id.et_test);
        tv_remainCount = (TextView) findViewById(R.id.ma_tv_remainCount);
        tv_terminal.setText(sp.getString("gateNo", ""));
        tv_pCount.setText("" + count);
        img_ip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText et = new EditText(MainActivity.this);
//                et.setHint("192.168.8.8:8888/Base");
                et.setHint("http://piaowu.taiyuanzoo.cn");
                et.setText("http://piaowu.taiyuanzoo.cn");
                String digital = "0123456789.:/qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
                et.setKeyListener(DigitsKeyListener.getInstance(digital));
//                若已经保存ip，则显示
                if (!sp.getString("ip", "").equals("")) {
                    et.setText(sp.getString("ip", ""));
                }
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("请输入ip地址")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (!(et.getText().toString().trim()).contains("http")) {
                                    ToastUtil.showToast("输入地址请包含  http://");
                                    return;
                                }
                                edit.putString("ip", et.getText().toString().trim());
                                edit.commit();

                                SPUtils.put(MainActivity.this, "ipString", et.getText().toString().trim());
//                                拼接IP地址
                                BaseURL.SERVER_URL = sp.getString("ip", "");
                                isIPset = true;
                                edit.putBoolean("isIPset", isIPset);
                                edit.commit();
//                                etTest.requestFocus();
//                                getGateList();
                                getGateListHttps();
                                ToastUtil.showToast("设置IP: " + et.getText().toString() + " 成功");

                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
//                                etTest.requestFocus();
                            }
                        }).show();
            }
        });
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("清空检票人数")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                count = 0;
                                edit.putInt("count", 0);
                                edit.commit();
                                tv_pCount.setText("" + count);
//                                etTest.requestFocus();
                                ToastUtil.showToast("清空人数成功");
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
//                                etTest.requestFocus();
                            }
                        }).show();

            }
        });

        et_input.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.d("key", "" + keyCode);
                if (keyCode == 66) {
                    Log.d("key", "" + keyCode);
//                    et_input.setText("");
//                    et_input.setBackground(new ColorDrawable(0xaa000000));
//                    et_input.setEnabled(false);
//                    mSwitchMultiButton.setSelectedTab(0);
                }
//                etTest.requestFocus();
                return false;
            }
        });

        img_link.setOnClickListener(this);


//        键盘监听事件
        SoftKeyBoardListener.setListener(MainActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            //            键盘显示
            @Override
            public void keyBoardShow(int height) {
//                Toast.makeText(AdjustResizeActivity.this, "键盘显示 高度" + height, Toast.LENGTH_SHORT).show();
            }

            //            键盘隐藏
            @Override
            public void keyBoardHide(int height) {
//                Toast.makeText(AdjustResizeActivity.this, "键盘隐藏 高度" + height, Toast.LENGTH_SHORT).show();
                //键盘隐藏后，设置switch为全检（false）。


            }
        });

    }


    private void getGateList() {
//        清空缓存，用于及时更新数据
        if (list != null) {
            list = null;
        }

        if (!isIPset) {
            ToastUtil.showToast("请设置ip地址");
            return;
        }

        String url = BaseURL.SERVER_URL + BaseURL.UNBINDPHONELIST;
        OkHttpUtils
                .get()
                .url(url)
                .addParams("userName", "admin")
                .addParams("password", "888888")
                .addParams("deskTerminalNo", getSerialNumber())
                .addParams("sign", "DDCA01EF3FF8B6C429D8FE406740539F")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.showToast("获取闸机列表失败，请检查ip设置");
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        try {
                            gateListResponse = new Gson().fromJson(response, GateListResponse.class);
                            if (gateListResponse.getCode().equals("0")) {

                                list = gateListResponse.getGateInfoList();
                                SPUtils.put(MainActivity.this, "gateNo", list.get(0).getGateNo());

                            } else {
                                ToastUtil.showToast("" + gateListResponse.getMessage());
                            }
                        } catch (Exception e) {
                            ToastUtil.showToast("获取闸机列表失败");

                        }
                    }

                });
    }


    /*https 请求方式测试*/

    private void getGateListHttps() {
        //构建 requset
        okhttp3.RequestBody requestBody = new okhttp3.FormBody.Builder()
                .add("userName", "admin")
                .add("password", "888888")
                .add("sign", "DDCA01EF3FF8B6C429D8FE406740539F")
                .build();

        OkHttpClient build = new OkHttpClient.Builder()
                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier(new TrustAllHostnameVerifier())
                .build();
//        String url = "https://wechat.thecrystalrccq.com/handSetCheckTicketJson/getGateList.do";//带https的网址
        String url = BaseURL.SERVER_URL + BaseURL.UNBINDPHONELIST;
        final Request request = new Request.Builder().url(url)
                .post(requestBody)
                .build();
        Call call = build.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast("网络请求失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    gateListResponse = new Gson().fromJson(res, GateListResponse.class);
                    if (gateListResponse.getCode().equals("0")) {

                        list = gateListResponse.getGateInfoList();

                    } else {
                        ToastUtil.showToast("" + gateListResponse.getMessage());
                    }
                } catch (Exception e) {
                    ToastUtil.showToast("获取闸机列表失败");
                }
            }
        });

    }


    private void checkQRCode(final String barcodeStr) {

        clearText();
        if (!isIPset) {
            ToastUtil.showToast("请设置ip地址");
            return;
        }
//        判断输入框是否输入了数据
        if (et_input.getText().toString().trim().length() > 0) {
            int value = Integer.valueOf(et_input.getText().toString().trim());
            if (value <= 0 || value > 1000) {
                ToastUtil.showToast("请输入合法数据");
                return;
            }
        }


        String url = BaseURL.SERVER_URL + BaseURL.CHECKTICKET;
        String sp_gateN0 = sp.getString("gateNo", "");
        if ("".equals(sp_gateN0)) {
            ToastUtil.showToast("请选择设备终端");
            return;
        }
        if (mSwitchMultiButton.getSelectedTab() == 1 && et_input.getText().toString().trim().equals("")) {
            ToastUtil.showToast("请输入检票数量");
//            etTest.requestFocus();
            return;
        }

        int checkCount = mSwitchMultiButton.getSelectedTab() == 1 ? Integer.valueOf(et_input.getText().toString().trim()) : -1;


        try {
            OkHttpUtils
                    .get()
                    .url(url)
                    .addParams("ticketNo", barcodeStr)
                    .addParams("userName", "admin ")
                    .addParams("password", "888888 ")
                    .addParams("gateNo", sp_gateN0)
                    .addParams("checkCount", "" + checkCount)
                    .addParams("sign", "FC2C7EC3C74BC8EA2A5F4C894323B5B7 ")
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ToastUtil.showToast("检票失败");
                        }

                        @Override
                        public void onResponse(String response, int id) {

                            //将String类型转换成json类型
                            JSONObject object = null;
                            try {
                                object = XML.toJSONObject(response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            String jsonData = object.toString();        //转换为json字符串。
                            Log.d("", "" + jsonData);
                            CheckTicketResponse response1 = new Gson().fromJson(jsonData, CheckTicketResponse.class);
                            if (0 == (response1.getCheckTicketMessageResult().getCode())) {

                                tv_terminal.setText(sp.getString("gateNo", ""));
                                tv_ticketNO.setText(barcodeStr);
                                tv_time.setText(response1.getCheckTicketMessageResult().getCheckTime());
                                tv_status.setText(response1.getCheckTicketMessageResult().getMsg());
                                tv_name.setText(response1.getCheckTicketMessageResult().getTicketName());
                                tv_people.setText("" + response1.getCheckTicketMessageResult().getTotalMaxNumber());
                                tv_remainCount.setText(response1.getCheckTicketMessageResult().getRestCheckCount());
                                count = count + response1.getCheckTicketMessageResult().getTotalMaxNumber();
                                tv_pCount.setText("" + count);
                                img_status.setImageResource(R.drawable.background_pass);

                                ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);
                                mSwitchMultiButton.setSelectedTab(0);
//                                etTest.requestFocus();
                            } else {
                                if (!TextUtils.isEmpty(response1.getCheckTicketMessageResult().getLastCheckTime())) {
                                    tv_time.setText(response1.getCheckTicketMessageResult().getLastCheckTime());
                                }
                                img_status.setImageResource(R.drawable.background_error);
                                ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);
                                mSwitchMultiButton.setSelectedTab(0);
//                                etTest.requestFocus();

                            }

                        }

                    });
        } catch (Exception e) {
            ToastUtil.showToast(e.toString());
        }

    }


    private void checkICCard(final String ICCardNO) {
        clearText();
        if (!isIPset) {
            ToastUtil.showToast("请设置ip地址");
            return;
        }
        String url = BaseURL.SERVER_URL + BaseURL.CHECKTICKET;
        String sp_gateN0 = sp.getString("gateNo", "");
        if ("".equals(sp_gateN0)) {
            ToastUtil.showToast("请先选择设备终端");
            return;
        }

        OkHttpUtils
                .get()
                .url(url)
                .addParams("certificateNo", ICCardNO)
                .addParams("userName", "admin ")
                .addParams("password", "888888 ")
                .addParams("gateNo", sp_gateN0)
                .addParams("sign", "FC2C7EC3C74BC8EA2A5F4C894323B5B7 ")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.showToast(e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        //将String类型转换成json类型
                        JSONObject object = null;
                        try {
                            object = XML.toJSONObject(response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        String jsonData = object.toString();        //转换为json字符串。
                        Log.d("", "" + jsonData);
                        CheckTicketResponse response1 = new Gson().fromJson(jsonData, CheckTicketResponse.class);
                        if (0 == (response1.getCheckTicketMessageResult().getCode())) {
                            tv_terminal.setText(sp.getString("gateNo", ""));
                            tv_ticketNO.setText(ICCardNO);
                            tv_time.setText(response1.getCheckTicketMessageResult().getCheckTime());
                            tv_status.setText(response1.getCheckTicketMessageResult().getMsg());
                            tv_name.setText(response1.getCheckTicketMessageResult().getTicketName());
                            tv_people.setText("" + response1.getCheckTicketMessageResult().getTotalMaxNumber());
                            count = count + 1;
                            tv_pCount.setText("" + count);
                            img_status.setImageResource(R.drawable.background_pass);
                            ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);
                            mSwitchMultiButton.setSelectedTab(0);
                        } else {
                            img_status.setImageResource(R.drawable.background_error);
                            ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);

                        }
                    }
                });
    }


    public void clearText() {
        tv_ticketNO.setText("");
        tv_time.setText("");
        tv_status.setText("");
        tv_name.setText("");
        tv_people.setText("");
    }

    @Override
    public void onClick(View v) {
        if (!isIPset) {
            ToastUtil.showToast("请设置ip地址");
            return;
        }
        View view = View.inflate(this, R.layout.popupwindow_ma_layout, null); //引入布局
        //获取PopupWindow中View的宽高
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        //将布局view传参给popupwindow
        popupWindow = new PopupWindow(view, screenWidth, screenHeight * 3 / 5);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xaa000000));//设置背景

        popupWindow.setFocusable(true);//popupwindow设置焦点
        popupWindow.setOutsideTouchable(true);//点击外面窗口消失
        popupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        setOnPopupViewClick(view);
        popupWindow.setAnimationStyle(android.R.style.Animation_Translucent);//设置动画

    }

    private void setOnPopupViewClick(View view) {

        ImageView img_close = (ImageView) view.findViewById(R.id.pop_img_close);
        final ListView pop_list = (ListView) view.findViewById(R.id.pop_list);
        final PopListAdapter adapter;
        if (list != null && list.size() > 0) {
            adapter = new PopListAdapter(getBaseContext(), list);
            pop_list.setAdapter(adapter);
        } else {
            ToastUtil.showToast("闸机列表为空，请检查IP设置");
            return;
        }

        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                etTest.requestFocus();
                popupWindow.dismiss();
            }
        });
        pop_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                edit.putInt("position", position);
//                edit.putString("gateName", list.get(position).getGateName());
                edit.putString("gateNo", list.get(position).getGateNo());

                edit.commit();

                tv_terminal.setText(list.get(position).getGateNo());
                adapter.notifyDataSetChanged();
                ToastUtil.showToast("选中 " + list.get(position).getGateNo() + " 成功");
            }
        });
    }

    public void ShowMsg(String Msg, int type, int PlayOrNot) {
        switch (type) {
            case 0:
                PlayAudioFile(Msg);
                break;

        }
    }

    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINA);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        } else {
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_ADD, null);
    }

    @Override
    protected void onStart() {
        super.onStart();

        Intent intent = new Intent(MainActivity.this, HeartBeatService.class);
        //启动FloatViewService
        startService(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("key", "" + keyCode);
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            Log.d("key", "" + keyCode);
            et_input.setText("");
            et_input.setBackground(new ColorDrawable(0xaa000000));
            et_input.setEnabled(false);
        }

        return true;
    }


    @Override
    protected void onPause() {
        super.onPause();
        edit.putInt("count", count);
        edit.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        flag = false;
        edit.putInt("count", count);
        edit.commit();
        IDCardReaderFactory.destroy(idCardReader);
        // 关闭扫描枪
        if (sm != null) {
            sm.stopScan();
        }
        unregisterReceiver(mScanReceiver);

        //清空所有Cookie
        CookieSyncManager.createInstance(this);  //Create a singleton CookieSyncManager within a context
        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
        cookieManager.removeAllCookie();// Removes all cookies.
        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now
    }

    private String getSerialNumber() {
        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }

    private static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private void checkQRCodeHttps(final String barcodeStr) {

        clearText();
        if (!isIPset) {
            ToastUtil.showToast("请设置ip地址");
            return;
        }
//        判断输入框是否输入了数据
        if (et_input.getText().toString().trim().length() > 0) {
            int value = Integer.valueOf(et_input.getText().toString().trim());
            if (value <= 0 || value > 1000) {
                ToastUtil.showToast("请输入合法数据");
                return;
            }
        }


        String url = BaseURL.SERVER_URL + BaseURL.CHECKTICKET;
        String sp_gateN0 = sp.getString("gateNo", "");
        if ("".equals(sp_gateN0)) {
            ToastUtil.showToast("请选择设备终端");
            return;
        }
        if (mSwitchMultiButton.getSelectedTab() == 1 && et_input.getText().toString().trim().equals("")) {
            ToastUtil.showToast("请输入检票数量");
//            etTest.requestFocus();
            return;
        }

        int checkCount = mSwitchMultiButton.getSelectedTab() == 1 ? Integer.valueOf(et_input.getText().toString().trim()) : -1;

        //ok

        //构建 requset
        okhttp3.RequestBody requestBody = new okhttp3.FormBody.Builder()
                .add("ticketNo", barcodeStr)
                .add("userName", "admin")
                .add("password", "888888")
                .add("gateNo", sp_gateN0)
                .add("checkCount", "" + checkCount)
                .add("sign", "FC2C7EC3C74BC8EA2A5F4C894323B5B7")
                .build();

        OkHttpClient build = new OkHttpClient.Builder()
                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier(new TrustAllHostnameVerifier())
                .build();

        final Request request = new Request.Builder().url(url)
                .post(requestBody).build();
        Call call = build.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("joker", "网络请求失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showToast("网络请求失败");
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.i("joker", res);
                //将String类型转换成json类型
                JSONObject object = null;
                try {
                    object = XML.toJSONObject(res);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String jsonData = object.toString();        //转换为json字符串。
                final CheckTicketResponse response1 = new Gson().fromJson(jsonData, CheckTicketResponse.class);
                try {
                    if (0 == (response1.getCheckTicketMessageResult().getCode())) {

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_terminal.setText(sp.getString("gateNo", ""));
                                tv_ticketNO.setText(barcodeStr);
                                tv_time.setText(response1.getCheckTicketMessageResult().getCheckTime());
                                tv_status.setText(response1.getCheckTicketMessageResult().getMsg());
                                tv_name.setText(response1.getCheckTicketMessageResult().getTicketName());
                                tv_people.setText("" + response1.getCheckTicketMessageResult().getTotalMaxNumber());
                                String restCheckCount = response1.getCheckTicketMessageResult().getRestCheckCount();
                                if (restCheckCount != null && !restCheckCount.equals("")){
                                    tv_remainCount.setText(restCheckCount);
                                }
                                count = count + response1.getCheckTicketMessageResult().getTotalMaxNumber();
                                tv_pCount.setText("" + count);
                                img_status.setImageResource(R.drawable.background_pass);
                                ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID() + response1.getCheckTicketMessageResult().getTicketName() + "可通行" + response1.getCheckTicketMessageResult().getTotalMaxNumber() + "人", 0, 0);
                                mSwitchMultiButton.setSelectedTab(0);
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);
                                mSwitchMultiButton.setSelectedTab(0);
                                img_status.setImageResource(R.drawable.background_error);
                            }
                        });

//                        etTest.requestFocus();
                    }
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("请求失败");
                        }
                    });

                }


            }
        });

//        try {
//            OkHttpUtils
//                    .get()
//                    .url(url)
//                    .addParams("ticketNo", barcodeStr)
//                    .addParams("userName", "admin")
//                    .addParams("password", "888888")
//                    .addParams("gateNo", sp_gateN0)
//                    .addParams("checkCount", "" + checkCount)
//                    .addParams("sign", "FC2C7EC3C74BC8EA2A5F4C894323B5B7")
//                    .build()
//                    .execute(new StringCallback() {
//                        @Override
//                        public void onError(Call call, Exception e, int id) {
//                            ToastUtil.showToast("检票失败");
//                        }
//
//                        @Override
//                        public void onResponse(String response, int id) {
//
//                            //将String类型转换成json类型
//                            JSONObject object = null;
//                            try {
//                                object = XML.toJSONObject(response);
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//
//                            String jsonData = object.toString();        //转换为json字符串。
//                            Log.d("", "" + jsonData);
//                            CheckTicketResponse response1 = new Gson().fromJson(jsonData, CheckTicketResponse.class);
//                            if (0 == (response1.getCheckTicketMessageResult().getCode())) {
//
//                                tv_terminal.setText(sp.getString("gateNo", ""));
//                                tv_ticketNO.setText(barcodeStr);
//                                tv_time.setText(response1.getCheckTicketMessageResult().getCheckTime());
//                                tv_status.setText(response1.getCheckTicketMessageResult().getMsg());
//                                tv_name.setText(response1.getCheckTicketMessageResult().getTicketName());
//                                tv_people.setText("" + response1.getCheckTicketMessageResult().getTotalMaxNumber());
//
//                                count = count + response1.getCheckTicketMessageResult().getTotalMaxNumber();
//                                tv_pCount.setText("" + count);
//                                img_status.setImageResource(R.drawable.background_pass);
//                                ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);
//                                mSwitchMultiButton.setSelectedTab(0);
//
//                            } else {
//                                img_status.setImageResource(R.drawable.background_error);
//                                ShowMsg(response1.getCheckTicketMessageResult().getGateSoundID(), 0, 0);
//                                mSwitchMultiButton.setSelectedTab(0);
//
//
//                            }
//
//                        }
//
//                    });
//        } catch (Exception e) {
//            ToastUtil.showToast(e.toString());
//        }

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
//
//            etTest.setText("");
            if (event.getKeyCode() == 120) {
                //如果是 扫描按钮，那么就去获取焦点
                etTest.requestFocus();
            }
            char pressedKey = (char) event.getUnicodeChar();
            barcode += pressedKey;
        }
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {

            if (barcode != null && !barcode.equals("")) {
                // 那么就去请求服务器
//                SelfToastUtil.getInstance(AnhuiActivity.this).show(etScan.getText().toString());
                barcodeStr = etTest.getText().toString().trim();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (barcodeStr != null && !barcodeStr.equals(""))//&& barcodeStrAgain != barcodeStr
                        {
                            checkQRCodeHttps(barcodeStr);
                        }
                        tv_ticketNO.setText(barcodeStr);
                        barcode = "";
                        etTest.setText("");
                    }
                });

//                Message message = Message.obtain();
//                message.what = ReadQR;
//                Bundle bundle = new Bundle();
//                message.setData(bundle);
//                mHandler.sendMessage(message);

            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showToast("未扫描到数据 为空");
                    }
                });
            }
        }
        return super.dispatchKeyEvent(event);
    }


}
